package com.story.api.moduler.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.story.api.common.persistence.dao.PlayRecordMapper;
import com.story.api.common.persistence.dao.SongListDetailMapper;
import com.story.api.common.persistence.model.*;
import com.story.api.common.result.PageResult;
import com.story.api.common.result.ServerResponse;
import com.story.api.common.util.PageBeanUtil;
import com.story.api.config.properties.UpyunProperties;
import com.story.api.moduler.song.dao.IndexPictureDao;
import com.story.api.moduler.upyun.service.UpyunService;
import com.story.api.moduler.user.dao.*;
import com.story.api.moduler.user.service.UserService;
import com.story.api.moduler.user.constant.LoginType;
import com.story.core.util.DateUtil;
import com.story.core.util.MD5Util;
import com.story.core.util.UriUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Administrator
 * @decription 用户相关服务
 * @Date 2017-12-14 17:14
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    private static final String DEFAULT_SONG_LIST = "睡前摇篮曲";

    private static final Long EXPIRE_TIME = 3600L;

    @Autowired
    private AppUserDao userDao;

    @Autowired
    private UserLoginDao userLoginDao;

    @Autowired
    private SongListDao songListDao;

    @Autowired
    private IndexPictureDao indexPictureDao;

    @Autowired
    private SongListDetailDao songListDetailDao;

    @Autowired
    private SongListDetailMapper songListDetailMapper;

    @Autowired
    private UserSongListDao userSongListDao;

    @Autowired
    private UpyunService upyunService;

    @Autowired
    private UpyunProperties upyunProperties;

    @Autowired
    private PlayRecordMapper playRecordMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse register(String phoneNum, String password) {
        //1.校验用户名是否已存在
        int count = userLoginDao.existPhone(phoneNum);
        if(count > 0) {
            return ServerResponse.getErrorMessage("该手机号已被注册");
        }
        //2.新增用户数据
        AppUser user = new AppUser();
        user.setNickName(phoneNum);
        user.setPhone(phoneNum);
        user.setRegisterDate(DateUtil.parseDate(DateUtil.getDay()));
        userDao.saveUser(user);
        //3.新增用户登录数据
        UserLogin userLogin = new UserLogin();
        int userId = user.getId();
        userLogin.setUserId(userId);
        userLogin.setIdentityType(LoginType.PHONE_TYPE);
        userLogin.setIdentifier(phoneNum);
        userLogin.setCredential(MD5Util.encrypt(password));
        userLoginDao.saveUserLogin(userLogin);
        log.info(phoneNum+":注册成功");
        //4.为用户创建一个默认歌单
        SongList songList = new SongList();
        songList.setName(DEFAULT_SONG_LIST);
        //得到一个图片地址
        String pictureUrl = indexPictureDao.getPictureUrlLimit();
        pictureUrl = StringUtils.isBlank(pictureUrl) ? "" : pictureUrl;
        songList.setLogoPath(pictureUrl);
        songList.setUserId(user.getId());
        songListDao.createSongList(songList);
        return ServerResponse.getSuccess("注册成功");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse updateUser(Integer userId, String content,String type) {
        if("phone".equals(type)) {
            userDao.bindPhoneNum(userId,content);
        }
        if("nickName".equals(type)) {
            userDao.updateNickName(userId,content);
        }
        return ServerResponse.getSuccess("update success");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse createSongList(Integer userId, String songListName) {
        //判断名称是否重复
        int count = songListDao.existName(userId,songListName.trim());
        if(count > 0) {
            return ServerResponse.getErrorMessage("收藏名已存在");
        }
        List<String> pictureUrlList = indexPictureDao.getPircureList();
        Random random = new Random();
        int index = random.nextInt(pictureUrlList.size());
        String pictureUrl = pictureUrlList.get(index);
        SongList songList = new SongList();
        songList.setUserId(userId);
        songList.setLogoPath(pictureUrl);
        songList.setName(songListName);
        songListDao.createSongList(songList);
        songList.setLogoPath(addTokenUrl(songList.getLogoPath()));
        return ServerResponse.getSuccess("create success",songList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse updateSongList(Integer userId,Integer songListId,String songListName) {
        //判断名称是否重复
        int count = songListDao.existName(userId,songListName.trim());
        if(count > 0) {
            return ServerResponse.getErrorMessage("收藏名已存在");
        }
        songListDao.updateName(songListId,songListName);
        return ServerResponse.getSuccess("update success");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse deleteSongList(Integer userId, Integer songListId) {
        //1.删除歌单详情中对应数据
        songListDetailDao.deleteBySongListId(songListId);
        //2.删除歌单
        songListDao.deleteSongList(userId,songListId);
        return ServerResponse.getSuccess("delete success");
    }

    @Override
    public ServerResponse songListDetail(Integer currentPage, Integer pageSize,Integer songListId) {
        PageHelper.startPage(currentPage,pageSize);
        List<VedioDetail> vedioDetailList = songListDetailDao.getVedioDetailListBySongListId(songListId);
        dealVedioDetailList( vedioDetailList );
        PageResult<VedioDetail> pageResult = PageBeanUtil.toPageResult(vedioDetailList);
        return ServerResponse.getSuccess("success",pageResult);
    }

    /**
     * 处理视频详情信息
     * @param vedioDetailList
     */
    public void dealVedioDetailList(List<VedioDetail> vedioDetailList) {
        vedioDetailList.parallelStream().forEach(vedioDetail -> {
            vedioDetail.setPlayCount( RandomUtils.nextInt(5001)+50000);
            vedioDetail.setDownloadCount(RandomUtils.nextInt(51)+100);
            vedioDetail.setShareCount(RandomUtils.nextInt(20)+30);
            if(StringUtils.isNotBlank(vedioDetail.getLogoPath())) {
                vedioDetail.setLogoPath(addTokenUrl(vedioDetail.getLogoPath()));
            }
            if(StringUtils.isNotBlank(vedioDetail.getFilePath())) {
                vedioDetail.setFilePath(videoAddDomain(vedioDetail.getFilePath()));
            }
        });
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse addVedioToSongList(Integer songListId, Integer vedioId) {
        SongListDetail songListDetail = new SongListDetail();
        songListDetail.setSongListId(songListId);
        songListDetail.setVedioId(vedioId);
        songListDetailMapper.insert(songListDetail);
        return ServerResponse.getSuccess("add success");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse deleteVideoFromSongList(Integer songListId, Integer vedioId) {
        songListDetailDao.deleteByListIdAndVideoId(songListId,vedioId);
        return ServerResponse.getSuccess("delete success");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean updateUserAvatar(Integer userId, String avatar) {
        userDao.updateAvatar(userId,avatar);
        return true;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse updatePwd(String phoneNum, String password) {
        userLoginDao.updatePassword(phoneNum,MD5Util.encrypt(password));
        return ServerResponse.getSuccess("update password success");
    }

    @Override
    public boolean checkOldPassword(Integer userId, String oldPassword) {
        int count = userLoginDao.checkOldPassword(userId,MD5Util.encrypt(oldPassword));
        if(count == 1) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updatePwdByUserId(Integer userId, String password) {
        userLoginDao.updatePwdByUserId(userId,MD5Util.encrypt(password));
    }

    @Override
    public ServerResponse userVideoList(Integer currentPage, Integer pageSize, Integer userId,Integer resType) {
        PageHelper.startPage(currentPage,pageSize);
        List<VedioDetail> vedioDetailList = userSongListDao.pageUserSonglist(userId,resType);
        dealVedioDetailList(vedioDetailList);
        PageResult<VedioDetail> pageResult = PageBeanUtil.toPageResult(vedioDetailList);
        return ServerResponse.getSuccess("success",pageResult);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse userCollectVideo(Integer userId, Integer videoId) {
        userSongListDao.userCollectVideo(userId,videoId);
        return ServerResponse.getSuccess("创建成功");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse userDeleteVideo(Integer userId, Integer videoId) {
        userSongListDao.userDeleteVideo(userId,videoId);
        return ServerResponse.getSuccess("删除成功");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ServerResponse userBatchDelVideo(Integer userId, List<Integer> videoIdList) {
        userSongListDao.userBatchDelVideo(userId,videoIdList);
        return ServerResponse.getSuccess("删除成功");
    }

    @Override
    public ServerResponse isCollectVideo(Integer userId, Integer videoId) {
        int count = userSongListDao.isCollectVideo(userId,videoId);
        Map<String,Object> result = new HashMap<String,Object>();
        if(count > 0) {
            result.put("isCollected",true);
            return ServerResponse.getSuccess("exist",result);
        } else {
            result.put("isCollected",false);
            return ServerResponse.getSuccess("not exist",result);
        }
    }

    @Override
    public PageResult userPlayRecordList(Integer currentPage, Integer pageSize, Integer userId, Integer resType) {
        PageHelper.startPage(currentPage,pageSize);
        List<VedioDetail> vedioDetailList = playRecordMapper.userPlayResourcePagelist(userId,resType);
        dealVedioDetailList(vedioDetailList);
        PageResult<VedioDetail> pageResult = PageBeanUtil.toPageResult(vedioDetailList);
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delPlayRecord(List<Integer> resourceIds, Integer userId) {
        for (Integer resId : resourceIds) {
            PlayRecord playRecord = new PlayRecord();
            playRecord.setResourceId(resId);
            playRecord.setUserId(userId);
            playRecordMapper.delete(new EntityWrapper<>(playRecord));
        }
    }

    /**
     * 对url添加token,防止盗链
     * @param url
     * @return
     */
    private String addTokenUrl(String url) {
        return upyunProperties.getDomain() + url + "?_upt=" + upyunService.getTokenSign(UriUtil.getUri(url),EXPIRE_TIME);
    }

    /**
     * 对于视频只添加域名
     * @param url
     * @return
     */
    private String videoAddDomain(String url) {
        return upyunProperties.getDomain() + url;
    }
}
